package juc.ProducerCnosumer;

/**
 * 产品生产者工厂
 * @author 马迪迪
 * @description: TODO
 * @data 2025年09月15日22时39分
 */
public class GoodsProducerFactory {
    // 根据商品类型创建生产者
    public static Thread createProducer(Store store, Goods goods) {
        return new Thread(new Producer(store, goods), goods + "生产者");
    }

    // 生产者线程逻辑
    static class Producer implements Runnable {
        private final Store store;
        private final Goods goods;
        private static final long PRODUCE_TIME = 10000; // 生产耗时10秒

        public Producer(Store store, Goods goods) {
            this.store = store;
            this.goods = goods;
        }

        // 在 GoodsProducerFactory.Producer 类中
        @Override
        public void run() {
            while (store.isRunning()) {
                try {
                    // 根据库存情况动态调整生产间隔
                    // 库存越低，生产间隔越短
                    long dynamicProduceTime = calculateDynamicProduceTime();
                    Thread.sleep(dynamicProduceTime);
                    // 执行生产
                    store.produce(goods);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    break;
                }
            }
            System.out.printf("[%s] 停止生产%n", Thread.currentThread().getName());
        }

        private long calculateDynamicProduceTime() {
            // 可以根据当前库存动态计算生产时间
            // 此处为示例逻辑，可根据实际需求调整
            return PRODUCE_TIME;
        }

    }
}
